package cn.b.sky.admin.service.impl;

import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.admin.dao.AdminResourceDao;
import cn.b.sky.admin.model.BatchJobReport;
import cn.b.sky.admin.model.ResourceEntity;
import cn.b.sky.admin.model.condition.ResourceCondition;
import cn.b.sky.admin.service.AdminResourceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("adminResourceService")
public class AdminResourceServiceImpl implements AdminResourceService {
  
  private static final Logger LOG = LoggerFactory.getLogger(AdminResourceServiceImpl.class);

  @Autowired
  private AdminResourceDao adminResourceDao;

  @Override
  public List<ResourceEntity> selectResourceList(ResourceCondition resourceCondition) {
    if (resourceCondition != null) {
      return adminResourceDao.selectResourceList(resourceCondition);
    } else {
      return null;
    }
  }

  @Override
  public ResourceEntity selectResource(String resourcecode) {
    if (!StringUtils.isEmpty(resourcecode)) {
      return adminResourceDao.selectResource(resourcecode);
    } else {
      return null;
    }
  }

  @Override
  public int selectResourceCount(ResourceCondition resourceCondition) {
    if (resourceCondition != null) {
      return adminResourceDao.selectResourceCount(resourceCondition);
    } else {
      return 0;
    }
  }

  @Override
  public void insertResource(ResourceEntity resource) {
    if (resource != null) {
      adminResourceDao.insertResource(resource);
    }

  }

  @Override
  public void updateResource(ResourceEntity resource) {
    if (resource != null) {
      adminResourceDao.updateResource(resource);
    }

  }

  @Override
  public BatchJobReport deleteResource(String resourcecode) {
    String cause = "";
    Boolean success = true;
    try {
      adminResourceDao.deleteResource(resourcecode);
    } catch (Exception e) {
      LOG.error("{}", e);
      String errorMsg = e.getMessage();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = "数据已被使用,不能删除!";
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(resourcecode, cause, success,"zh");

  }

  @Override
  public List<ResourceEntity> selectAllUnLockResource() {
    return adminResourceDao.selectAllUnLockResource();
  }

}
